package jsyf.oa.service.psi;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.psi.GoodsDao;
import jsyf.oa.dao.psi.InventoryDao;
import jsyf.oa.dao.psi.PurchaseDao;
import jsyf.oa.dao.psi.RepoInOutDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.psi.GoodsEntity;
import jsyf.oa.entity.psi.InventoryEntity;
import jsyf.oa.entity.psi.PurchaseManiEntity;
import jsyf.oa.entity.psi.RepoInOutMainEntity;
import jsyf.oa.entity.system.*;
import jsyf.oa.entity.thurTrack.ThurTrackEntity;
import jsyf.oa.facade.psi.InventoryFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

/**
 * Created by Maqiuqiu on 2018/10/17.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class InventoryService implements InventoryFacade {
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RepoInOutDao repoInOutDao;
    @Autowired
    private GoodsDao goodsDao;

    @Override
    public String save(String jsonData) {
        InventoryEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), InventoryEntity.class);
        Integer rows;
        if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
            rows = inventoryDao.add(entity);
        } else {
            InventoryEntity inventoryEntity = (InventoryEntity) inventoryDao.getIBaseEntityById(entity.getId());
            inventoryEntity.setGoodsId(entity.getGoodsId());
            inventoryEntity.setRequirements(entity.getRequirements());
            inventoryEntity.setAddress(entity.getAddress());
            inventoryEntity.setCount(entity.getCount());
            inventoryEntity.setUnit(entity.getUnit());
            inventoryEntity.setPrice(entity.getPrice());
            inventoryEntity.setState(entity.getState());
            inventoryEntity.setExtra(entity.getExtra());
            inventoryEntity.setPurchaseId(entity.getPurchaseId());
            inventoryEntity.setRepoInOutId(entity.getRepoInOutId());
            inventoryEntity.setCreateUserId(entity.getCreateUserId());
            inventoryEntity.setCreateTime(entity.getCreateTime());
            inventoryEntity.setUpdateUserId(entity.getUpdateUserId());
            inventoryEntity.setUpdateTime(entity.getUpdateTime());
            rows = inventoryDao.update(inventoryEntity);
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public Boolean delById(String id) {
        return inventoryDao.delById(id) > 0;
    }

    @Override
    public JSONObject getInventoryList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String key = jsonParams.getString("key");
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND (t_psi_goods.`NAME` LIKE '%" + key + "%' " +
                    "OR t_psi_inventory.ADDRESS LIKE '%" + key + "%')");
        }
        condition.append(" AND t_psi_purchase.STATE = '3'  ");
        condition.append(" GROUP BY t_psi_goods.ID  ");
        condition.append(" ORDER BY t_psi_inventory.CREATE_TIME DESC   ");
        //查询list
        List<JSONObject> records = inventoryDao.getInventoryList(userId,condition.toString(),requestPage,pageSize);
        for (int i = 0; i < records.size(); i++) {
            JSONObject jsonObject = records.get(i);
            String goodsId = jsonObject.getString("goodsId");
            List<JSONObject> inventoryList = inventoryDao.getJSONListByCondition("AND GOODS_ID = ? AND PURCHASE_ID IS NOT NULL ",new Object[]{goodsId});
            int inCount = 0;
            int inCountALl = 0;
            int outCount = 0;
            int outCountAll = 0;
            int nowCount = 0;
            for (int j = 0; j < inventoryList.size(); j++) {
                JSONObject object1 = inventoryList.get(j);
                inCount = Integer.valueOf(object1.getString("count"));
            }
            inCountALl += inCount;
            List<JSONObject> repoList =
                    repoInOutDao.getJSONListByCondition("AND GOODS_ID = ? AND IN_OUT_FLAG = '0' AND AUDIT_FLAG = '1' ",new Object[]{goodsId});
            for (int k = 0; k < repoList.size(); k++) {
                JSONObject object2 = repoList.get(k);
                outCount = Integer.valueOf(object2.getString("count"));
            }
            outCountAll += outCount;
            if(inCountALl > outCountAll){
                nowCount = inCountALl - outCountAll;
            }else {
                nowCount = 0;
            }
            jsonObject.put("inCountALl",inCountALl);
            jsonObject.put("outCountAll",outCountAll);
            jsonObject.put("nowCount",nowCount);
        }
        //查询总数
        int recordCount = inventoryDao.getInventoryList(userId,condition.toString(), 1, Integer.MAX_VALUE).size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        //子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getOutRepoInfo(String jsonData){
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject results = new JSONObject();
        String goodsId = jsonParams.getString("goodsId");
        List<JSONObject> objectList =
                repoInOutDao.getJSONListByCondition("AND GOODS_ID = ? AND AUDIT_FLAG = 1",new Object[]{goodsId});
        results.put("outRepo",objectList);
        return results;
    }

    @Override
    public JSONObject getInventoryGoodsInfoById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject results = new JSONObject();
        String id = jsonParams.getString("id");
        JSONObject result = inventoryDao.getJSONById(id);
        JSONObject jsonObject = goodsDao.getJSONById(result.getString("goodsId"));
        result.put("goodsName",jsonObject.getString("name"));
        results.put("main", result);
        return results;
    }

    @Override
    public JSONObject applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        JSONObject result = new JSONObject();
        String id = jsonPalams.getString("id");
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("currentAuditorId");//当前审核人ID
        String userName = jsonPalams.getString("currentAuditorName");//当前审核人NAME
        String roleName = jsonPalams.getString("roleName");//当前审核人ROLENAME
        String advise = jsonPalams.getString("advise");//意见
        PurchaseManiEntity purchaseManiEntity = (PurchaseManiEntity) purchaseDao.getIBaseEntityById(id);
        //添加历史审核记录
        AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
        auditHistoryEntity.setAuditFlag(auditFlag);
        auditHistoryEntity.setMainId(id);
        auditHistoryEntity.setAuditAdvise(advise);
        auditHistoryEntity.setAuditorId(userId);
        auditHistoryEntity.setAuditorName(userName);
        auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
        auditHistoryEntity.setAuditType(8);
        auditHistoryDao.add(auditHistoryEntity);
        //更新当前审核人的--审核表记录
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object)
                auditDao.getIBaseEntityByCondition(" and MAIN_ID = ? and AUDITOR_ID = ? ", new Object[]{id, userId});
        if (null != auditEntityList && auditEntityList.size() > 0) {
            AuditEntity auditEntity = auditEntityList.get(0);
            auditEntity.setAuditFlag(Integer.parseInt(auditFlag));
            auditEntity.setAuditAdvise(advise);
            auditEntity.setAuditTime(auditDao.getCurrentTime());
            auditEntity.setAuditorName(userName);
            auditEntity.setRoleName(roleName);
            auditDao.update(auditEntity);
        }
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        List<AuditEntity> auditList =  (List<AuditEntity>) (Object)
                auditDao.getIBaseEntityByCondition("and MAIN_ID = ?  order by audit_sort", new Object[]{id});
        for (int i = 0; i < auditList.size(); i++) {
            AuditEntity audit = auditList.get(i);
            if (audit.getAuditorId().equals(userId)) {
                //如果是驳回，修改主表状态为驳回->2
                if (auditFlag.equals("2")) {
                    purchaseManiEntity.setAuditFlag("2");
                    purchaseDao.update(purchaseManiEntity);

                    //企业号:审核驳回，发消息通知申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", purchaseManiEntity.getCreateUserId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(TRUCK_AUDIT_REJECT,
                            purchaseManiEntity.getCreateUserName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

//                    //审核驳回，发送消息给申请人，保存消息到消息表t_sys_message
//                    MessageEntity messageCreateEntity = new MessageEntity();
//                    messageCreateEntity.setCreateUserId(purchaseManiEntity.getCreateUserId());
//                    messageCreateEntity.setCreateTime(purchaseDao.getCurrentTime());
//                    messageCreateEntity.setContent(String.format(TRUCK_AUDIT_REJECT,
//                            purchaseManiEntity.getCreateUserName(),
//                            audit.getAuditAdvise(),
//                            audit.getAuditorName(),
//                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
//                    messageCreateEntity.setMessageType(0);
//                    messageCreateEntity.setMainId(id);
//                    messageCreateEntity.setDelFlag(0);
//                    messageCreateEntity.setOpenUrl("/page/reportForm/salesForecastReport/thursdayTrack.html?id="
//                            + thurTrackEntity.getId() + "&pageType=look");
//                    messageCreateEntity.setOpenTitle(String.format(TRUCK_AUDIT_THREE,
//                            thurTrackEntity.getCustomerName(), audit.getAuditorName()));
//                    messageDao.add(messageCreateEntity);
//
//                    //审核驳回，发送消息给申请人,保存消息到消息收件人表t_sys_message_receiver
//                    MessageReceiverEntity messageCreateReceiverEntity = new MessageReceiverEntity();
//                    messageCreateReceiverEntity.setMessageId(messageCreateEntity.getId());
//                    messageCreateReceiverEntity.setUserId(purchaseManiEntity.getCreateUserId());
//                    messageCreateReceiverEntity.setUserType(2);
//                    messageCreateReceiverEntity.setReadFlag(0);
//                    messageReceiverDao.add(messageCreateReceiverEntity);
//
//                    //发消息
//                    jsonObjectList.add(getMessage(messageCreateEntity, messageCreateReceiverEntity));
//                    break;
                }
                //如果是最后一个人审核通过，标记主表状态为通过->1
                if (auditList.size() - 1 == i) {
                    purchaseManiEntity.setAuditFlag("1");
                    purchaseDao.update(purchaseManiEntity);

                    //企业号: 最后一个审核通过,发送消息给申请人
                    JSONObject msgObject = new JSONObject();
                    msgObject.put("userIds", purchaseManiEntity.getCreateUserId());
                    //msgObject.put("userIds", "2017121820434803834AA7E354A82ABB");
                    msgObject.put("content", String.format(TRUCK_AUDIT_PASS,
                            purchaseManiEntity.getCreateUserName(),
                            audit.getAuditorName(),
                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

//                    //审核通过，发送消息给申请人，保存消息到消息表t_sys_message
//                    MessageEntity msgAuditEntity = new MessageEntity();
//                    msgAuditEntity.setCreateUserId(purchaseManiEntity.getCreateUserId());
//                    msgAuditEntity.setCreateTime(purchaseDao.getCurrentTime());
//                    msgAuditEntity.setContent(String.format(TRUCK_AUDIT_PASS,
//                            purchaseManiEntity.getCreateUserName(),
//                            audit.getAuditorName(),
//                            DateUtils.parse(audit.getAuditTime(), "yyyy-MM-dd HH:mm")));
//                    msgAuditEntity.setMessageType(0);
//                    msgAuditEntity.setMainId(id);
//                    msgAuditEntity.setDelFlag(0);
//                    msgAuditEntity.setOpenUrl("/page/reportForm/salesForecastReport/thursdayTrack.html?id="
//                            + thurTrackEntity.getId() + "&pageType=look");
//                    msgAuditEntity.setOpenTitle(String.format(TRUCK_AUDIT_TWO, thurTrackEntity.getCustomerName(), audit.getAuditorName()));
//                    messageDao.add(msgAuditEntity);
//
//                    //审核通过，发送消息给申请人，保存消息到表t_sys_message_receiver
//                    MessageReceiverEntity msgReceiverEntity = new MessageReceiverEntity();
//                    msgReceiverEntity.setMessageId(msgAuditEntity.getId());
//                    msgReceiverEntity.setUserId(purchaseManiEntity.getCreateUserId());
//                    msgReceiverEntity.setUserType(2);
//                    msgReceiverEntity.setReadFlag(0);
//                    messageReceiverDao.add(msgReceiverEntity);
//
//                    //发消息
//                    jsonObjectList.add(getMessage(msgAuditEntity, msgReceiverEntity));
                }
            } else {
                //下一位审核人才进入，修改审核表状态和主表审核人信息
                if (audit.getAuditFlag().toString().equals("-1")) {
                    audit.setAuditFlag(0);
                    auditDao.update(audit);
                    purchaseManiEntity.setCurrentAuditorName(audit.getAuditorName());
                    purchaseManiEntity.setCurrentAuditorId(audit.getAuditorId());
                    purchaseManiEntity.setAuditFlag(audit.getAuditFlag().toString());
                    purchaseDao.update(purchaseManiEntity);
                    break;
                }
            }
        }
        //发消息
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }
}
